package com.allchips.pin.threads;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.allchips.pin.domain.PinInfoLc;
import com.allchips.pin.domain.PinInfoValue;
import com.allchips.pin.enums.PinInfoSyncEnum;
import com.allchips.pin.service.PinInfoLcService;
import com.allchips.pin.service.PinInfoValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gary
 * @date 2022年07月12日 11:58
 */
@Component
@Slf4j
public class SpecialPunctuationRunning {

    @Resource
    PinInfoLcService pinInfoLcService;

    @Resource
    PinInfoValueService pinInfoValueService;

    public boolean run() {
        boolean rtn = true;
        List<PinInfoLc> records;
        Integer curId = null;
        try {
            do {
                List<PinInfoLc> updateList = new ArrayList<>();
                LambdaQueryWrapper<PinInfoLc> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PinInfoLc::getSync, PinInfoSyncEnum.SYMBOL_2_STANDARD);
                queryWrapper.orderByAsc(PinInfoLc::getId);
                queryWrapper.select(PinInfoLc::getId, PinInfoLc::getPinDt);
                queryWrapper.last("limit 100");
                records = pinInfoLcService.list(queryWrapper);
                if (CollUtil.isEmpty(records)) {
                    break;
                }
                List<Integer> idList = new ArrayList<>();
                List<PinInfoValue> pinInfoValueList = new ArrayList<>();
                for (PinInfoLc k1 : records) {
                    curId = k1.getId();
                    idList.add(curId);

                    String pinDt = k1.getPinDt();
                    JSONObject jsonObject = JSONUtil.parseObj(pinDt);
                    Map<String, String> standardMap = new HashMap<>();
                    Set<String> values = new HashSet<>();
                    for (final Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                        String key = entry.getKey();
                        String value = Convert.toStr(entry.getValue());
                        value = standardValue(value);
                        standardMap.put(key.toLowerCase(), value);
                        values.addAll(Arrays.stream(value.split(" ")).collect(Collectors.toSet()));
                    }
                    if (CollUtil.isNotEmpty(values)) {
                        for (final String value : values) {
                            PinInfoValue pinInfoValue = new PinInfoValue();
                            pinInfoValue.setValue(value);
                            pinInfoValue.setPinId(curId);
                            pinInfoValueList.add(pinInfoValue);
                        }
                    }

                    PinInfoLc updateRecord = new PinInfoLc();
                    updateRecord.setId(k1.getId());
                    updateRecord.setStandardPinDt(JSONUtil.toJsonStr(standardMap));
                    updateRecord.setSync(PinInfoSyncEnum.SYMBOL_STANDARD.getStatusCode());
                    updateList.add(updateRecord);
                }
                //删除数据
                LambdaUpdateWrapper<PinInfoValue> updatePinInfoValue = new LambdaUpdateWrapper<>();
                updatePinInfoValue.in(PinInfoValue::getPinId, idList);
                pinInfoValueService.remove(updatePinInfoValue);
                //保存value数据
                pinInfoValueService.saveBatch(pinInfoValueList, 100);
                //更新pin信息
                pinInfoLcService.updateBatchById(updateList);
            } while (CollUtil.isNotEmpty(records));
        } catch (Exception e) {
            log.error("特殊字符转换异常", e);
            if (curId != null) {
                PinInfoLc update = new PinInfoLc();
                update.setId(curId);
                update.setSync(PinInfoSyncEnum.EXCEPTION_DATA.getStatusCode());
                pinInfoLcService.updateById(update);
            }
            rtn = false;
        }
        return rtn;
    }

    /**
     * 标准化值
     */
    private String standardValue(String value) {
        //为空返回
        if (StrUtil.isBlank(value)) {
            return "";
        }
        value = value.toLowerCase();
        value = value.replace(" ", "");
        value = value.replace("(+)", "+").replace("﹢", "+").replace("(-)", "-").replace("﹣", "-").replace("#", "").replace(".", "");
        value = value.replace("(", " ").replace(")", " ").replace("/", " ").replace("[", " ").replace("]", " ");
        //前后有-号不需要处理，否则需要处理
        if (!(value.charAt(0) == '-' || value.charAt(value.length() - 1) == '-')) {
            value = value.replace("-", " ");
        }
        if (StrUtil.isBlank(value)) {
            return "";
        }
        //判断是否有+-号在前的。挪到后面
        StringBuffer stringBuffer = new StringBuffer();
        String[] s = value.split(" ");
        for (int i = 0; i < s.length; i++) {
            String temp = s[i];
            if(StrUtil.isBlank(temp)){
                continue;
            }
            char s0 = temp.charAt(0);
            if (Objects.equals(s0, '-') || Objects.equals(s0, '+')) {
                s[i] = temp.substring(1) + s0;
            }
            if(stringBuffer.length()>0){
                stringBuffer.append(" ");
            }
            stringBuffer.append(s[i]);
        }
        return stringBuffer.toString();
    }

}